import Taro, { Component } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'

import './index.styl'

class Modal extends Component {
  constructor() {
    super(...arguments)
    this.state = {}
  }

  cancelClick = () => {
    // 打开设置
    this.props.onCancelCallback()
  }

  authConfirmClick = (e) => {
    console.log('用户信息')
    console.log(e.detail.userInfo)
    let code = ''
    // 登录
    Taro.login({}).then((res) => {
      console.log('用户登录成功')
      code = res.code
      // 请求用户授权 scope.userLocation
      return Taro.authorize({
        scope: 'scope.userLocation'
      })
    }).then(() => {
      console.log('请求用户授权 scope.userLocation 成功')
      // 获取用户地址
      return Taro.getLocation({type: 'gcj02'})
    }).then(data => {
      console.log('获取用户地址成功')
      console.log(data)
      // 将所有数据传回首页
      this.props.onConfirmCallback({
        code,
        userInfo: e.detail.userInfo,
        location: data
      })
    }).catch(err => {
      console.log('用户拒绝登录')
      console.log(err)
      // TODO 拒绝登录的处理
    })
  }

  componentDidMount () {
    console.log('loginModal show')
  }

  preventTouchMove = (e) => {
    e.stopPropagation()
  }

  render() {
    const { title, contentText} = this.props
    return (
      <View class='toplife_modal' onTouchMove={this.preventTouchMove}>
        <View class='toplife_modal_content'>
          <View class='toplife_modal_title'>{title}</View>
          <View class='toplife_modal_text'>{contentText}</View>
          <View class='toplife_modal_btns'>
            <Button class='toplife_modal_btn toplife_modal_btn_confirm' openType='getUserInfo' onGetuserinfo={this.authConfirmClick}>授权</Button>
          </View>
        </View>
      </View>
    )
  }
}

Modal.defaultProps = {
  title: '',
  contentText: '',
  cancelText: '取消',
  confirmText: '确定',
  cancelCallback: () => {},
  confirmCallback: () => {},
}

export default Modal
